package com.qeeyou.apps.android.craftsman.activity.login;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.event.LoginEvent;
import com.qeeyou.apps.android.craftsman.po.LoginInfo;
import com.qeeyou.apps.android.craftsman.po.RegisterInfo;
import com.qeeyou.apps.android.craftsman.service.SystemContext;
import com.qeeyou.apps.android.craftsman.service.UserService;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class RegisterActivity extends Activity {

    private EditText editUsername;
    private EditText editVerifyCode;
    private Button btnVerifyCode;
    private EditText editPassword;
    private Button btnRegister;
    private Button btnAccountLogin;
    private Button btnSMSLogin;
    private CustomLoadingDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        setView();

        setEvent();
    }

    private void setView() {
        editUsername = (EditText) this.findViewById(R.id.editMobile4Register);
        editVerifyCode = (EditText) this.findViewById(R.id.editVerifyCode4Register);
        editPassword = (EditText) this.findViewById(R.id.editPassword4Register);
        btnVerifyCode = (Button) this.findViewById(R.id.btnVerifyCode4Register);
        btnRegister = (Button) this.findViewById(R.id.btnRegister4Register);
        btnAccountLogin = (Button) this.findViewById(R.id.btnAccountLogin4Register);
        btnSMSLogin = (Button) this.findViewById(R.id.btnSMSLogin4Register);
    }

    private void setEvent() {

        btnRegister.setOnClickListener(onRegisterClickListener);

        btnVerifyCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new GetVerifyCodeAction().execute();
            }
        });

        btnAccountLogin.setOnClickListener(onLoginClickListener);
        btnSMSLogin.setOnClickListener(onLoginClickListener);
    }

    private View.OnClickListener onRegisterClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String username = editUsername.getText().toString();
            String password = editPassword.getText().toString();
            String verifyCode = editVerifyCode.getText().toString();
            if (username == null || username.trim().equalsIgnoreCase("")) {
                Toast.makeText(RegisterActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password == null || password.trim().equalsIgnoreCase("")) {
                Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (verifyCode == null || verifyCode.trim().equalsIgnoreCase("")) {
                Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            String[] params = {username, password};
            new UserRegisterAction().execute(params);

        }
    };

    private View.OnClickListener onLoginClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            RegisterActivity.this.finish();
        }
    };

    public class UserRegisterAction extends AsyncTask<String, Void, RegisterInfo> {
        private String username;
        private String password;

        public UserRegisterAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mProgressDialog == null) {
                mProgressDialog = new CustomLoadingDialog(RegisterActivity.this);
            }
            mProgressDialog.setMessage("正在注册...");
            mProgressDialog.show();
        }

        @Override
        protected void onPostExecute(RegisterInfo registerInfo) {
            super.onPostExecute(registerInfo);
            if (registerInfo != null) {
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                SystemContext.getInstance().setUsername(username);
                SystemContext.getInstance().setPassword(password);
                SystemContext.getInstance().setToken(registerInfo.getToken());
                SystemContext.getInstance().setUserId(registerInfo.getUserid());
                String[] params = new String[] {username, password};
                new AutoLoginAction().execute(params);
            } else {
                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected RegisterInfo doInBackground(String... params) {
            username = params[0];
            password = params[1];
            String coordinates = "121.351303, 31.387385";
            String address = "上海市罗贤路388弄11号楼";
            Map<String, String> parameters = new HashMap<>();
            parameters.put("accountName", username);
            parameters.put("accountPass", password);
            parameters.put("coordinates", coordinates);
            parameters.put("address", address);
            RegisterInfo info = UserService.getInstance().userRegister(parameters);
            return info;
        }
    }

    //自动登录
    public class AutoLoginAction extends AsyncTask<String, Void, LoginInfo> {
        private String username;
        private String password;

        public AutoLoginAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mProgressDialog == null) {
                mProgressDialog = new CustomLoadingDialog(RegisterActivity.this);
            }
            mProgressDialog.setMessage("正在注册...");
            mProgressDialog.show();
        }

        @Override
        protected void onPostExecute(LoginInfo loginInfo) {
            super.onPostExecute(loginInfo);
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
            if (loginInfo != null) {
                SystemContext.getInstance().setUsername(username);
                SystemContext.getInstance().setPassword(password);
                SystemContext.getInstance().setLoginInfo(loginInfo);
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                EventBus.getDefault().post(new LoginEvent());
                RegisterActivity.this.setResult(RESULT_OK);
                RegisterActivity.this.finish();
            } else {
                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected LoginInfo doInBackground(String... params) {
            username = params[0];
            password = params[1];
            Map<String, String> parameter = new HashMap<>();
            parameter.put("username", username);
            parameter.put("password", password);
            LoginInfo info = UserService.getInstance().userLogin(parameter);
            return info;
        }
    }

    //获取验证码
    public class GetVerifyCodeAction extends AsyncTask<String, Void, String> {

        public GetVerifyCodeAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mProgressDialog == null) {
                mProgressDialog = new CustomLoadingDialog(RegisterActivity.this);
            }
            mProgressDialog.setMessage("正在获取验证码...");
            mProgressDialog.show();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
            if(result != null) {
                editVerifyCode.setText(result);
            }
            Toast.makeText(RegisterActivity.this, "获取验证码成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(String... params) {
            String result = "123456";
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            result = getRandomString(6);
            return result;
        }

        private String getRandomString(int length) { //length表示生成字符串的长度
            String base = "0123456789";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
        }
    }
}
